import WujieVue from 'wujie-vue3'
import { hostMap, lifecycles } from '@/wujie/config'
import {
  EventTargetPlugin,
  InstanceofPlugin,
  SelectionPlugin,
  DocFullscreenPlugin
} from 'wujie-polyfill'
import { goLogin } from '@common'
const { setupApp, preloadApp } = WujieVue
const setupApps = () => {
  hostMap().forEach((v) => {
    const data = {
      ...v,
      ...lifecycles,
      plugins: [
        EventTargetPlugin(),
        SelectionPlugin(),
        InstanceofPlugin(),
        DocFullscreenPlugin(),
        {
          jsBeforeLoaders: [
            {
              callback: (appWindow) => {
                Object.defineProperties(appWindow, {
                  Selection: {
                    get: () =>
                      appWindow.__WUJIE.degrade
                        ? appWindow.__WUJIE.document.defaultView.Selection
                        : appWindow.parent.Selection
                  },
                  DataTransfer: {
                    get: () =>
                      appWindow.__WUJIE.degrade
                        ? appWindow.__WUJIE.document.defaultView.DataTransfer
                        : appWindow.parent.DataTransfer
                  }
                })
              }
            }
          ],
          jsLoader: (code) => {
            return code
              .replace(
                'e instanceof t.Node',
                'e instanceof (window.__WUJIE.degrade ? window.Node : t.Node)'
              )
              .replace('n.isCollapsed', 'n.baseOffset === n.focusOffset')
              .replace('n.collapsed', 'n.startOffset === n.endOffset')
          }
        }
      ]
    }
    setupApp({
      ...data
    })
    if (data.preload) {
      preloadApp({ ...data })
    }
  })
}
setupApps()
WujieVue.bus.$on('login', () => {
  goLogin()
})
// 子服务路由变更时通知主服务
WujieVue.bus.$on('sub-main-route', ({ appId, data }) => {
  // 所有服务
  console.log(`${appId}--路由切换-${data}`)
  window.history.replaceState({}, '', `${window.location.origin}/#${data}`)
})

export default WujieVue
